import React, {Component} from 'react';
import {ScrollView, View, Text, Button, TextInput, FlatList, StyleSheet, TouchableOpacity} from 'react-native';
import {StackActions, NavigationActions} from 'react-navigation';
import {Avatar, ListItem, Input, Image, Rating, AirbnbRating, Divider} from 'react-native-elements';
import {serverUrl} from '../app.json';
import axios from 'axios';
import ImagePicker from 'react-native-image-picker';
import RNFetchBlob from 'rn-fetch-blob';

const rateList = ['很差', '差', '中', '良', '优'];
const options = {
    title: '选择照片',
    storageOptions: {
        skipBackup: true,
        path: 'images',
    },
};

export default class logScreen extends Component {
    constructor(props) {
        super(props);
        this.state = {
            tree: '',
            treeName: null,
            description: '果树健康',
            state: 3,
            picSource: null,
            logList: [],
        };
        this.fetchData = this.fetchData.bind(this);
        this.handleTakePicButtonClick = this.handleTakePicButtonClick.bind(this);
        this.handleSaveButtonClick = this.handleSaveButtonClick.bind(this);
    }

    static navigationOptions = ({navigation, navigationOptions}) => {
        return {
            title: '日志',
        };
    };

    // 根据果树id获取果树的日志列表
    fetchData() {
        let treeName = this.props.navigation.getParam('treeName', '');
        this.setState({treeId: treeName});
        axios.get(serverUrl + '/getTreeByName/{name}?name=' + treeName)
            .then((response) => {
                let tree = response.data;
                this.setState({tree: tree});
            })
            .catch(function (error) {
                alert(error);
            });

        axios.get(serverUrl + '/getTreeLogByTreeName/{name}?name=' + treeName)
            .then((response) => {
                console.log(response.data);
                this.setState({
                    logList: response.data,
                });
            })
            .catch(function (error) {
                console.log(error);
                alert(error);
            });
    }

    componentDidMount() {
        this.fetchData();
    }

    // 选取图片
    handleTakePicButtonClick() {
        ImagePicker.showImagePicker(options, (response) => {
            console.log('Response = ', response);
            if (response.didCancel) {
                console.log('User cancelled image picker');
            } else if (response.error) {
                console.log('ImagePicker Error: ', response.error);
            } else if (response.customButton) {
                console.log('User tapped custom button: ', response.customButton);
            } else {
                this.setState({
                    picSource: response,
                });
            }
        });
    }

    // 保存果树日志，日志图片
    handleSaveButtonClick() {
        // 保存果树日志
        axios.post(serverUrl + '/saveTreeLog', {
            'description': this.state.tree.description,
            'state': this.state.tree.state,
            'treeName': this.state.tree.name,
            'picNames': this.state.picSource != null ? this.state.picSource.fileName : '',
        }).then((response) => {
            this.setState({
                logList: response.data,
            });
        }).catch(function (error) {
            alert(error);
        });
        // 保存图片
        if (this.state.picSource != null) {
            console.log('save pic',this.state.picSource);
            RNFetchBlob.fetch('POST', serverUrl + '/upLoadFiles', {'Content-Type': 'multipart/form-data'},
                [
                    {
                        name: 'files',
                        filename: this.state.picSource.fileName,
                        type: 'image/jpeg',
                        data: RNFetchBlob.wrap(this.state.picSource.uri),
                    },
                    {name: 'treeName', data: this.state.tree.name},
                ])
                .then((response) => {
                    alert(response.text());
                    return response.text();
                })
                .catch(error => console.log(error));
        }
    }

    _createListItem(item) {
        return (
            <TouchableOpacity activeOpacity={0.5}>
                <View style={styles.row}>
                    <View>
                        <Avatar
                            rounded
                            source={{
                                uri:
                                    'https://www.baidu.com/img/bd_logo1.png',
                            }}
                        />
                    </View>
                    <View style={{padding: 10}}>
                        <View style={{flexDirection: 'row'}}>
                            <Text>{item.recordTime.substr(0, 10)}</Text>
                            <Text style={{marginLeft: 10}}>{rateList[item.state]}</Text>
                        </View>
                        <Text>{item.description}</Text>
                        {
                            item.picNames != '' &&(
                                <Image
                                    source={{uri: serverUrl + '/static/treeData/'+item.treeName+'/'+item.picNames}}
                                    style={{width: 200, height: 200}}
                                />
                            )
                        }
                    </View>
                </View>
            </TouchableOpacity>
        );
    }

    render() {
        return (
            <ScrollView style={styles.container}>
                <View style={{padding: 10}}>
                    <View>
                        <Text>状态：</Text>
                        <AirbnbRating
                            count={5}
                            reviews={['很差', '差', '中', '良', '优']}
                            defaultRating={this.state.tree.state}
                            size={20}
                        />
                    </View>
                    <View>
                        <Text>描述：</Text>
                        <TextInput
                            multiline={true}
                            numberOfLines={4}
                            style={{height: 40, borderColor: 'gray', borderWidth: 1}}
                            onChangeText={(text) => {
                                let data = Object.assign({}, this.state.tree, {description: text});
                                this.setState({tree: data});
                            }}
                            value={this.state.tree.description}
                        />
                    </View>
                    <View style={{flexDirection: 'row', margin: 10}}>
                        <View style={{flex: 1, margin: 10}}>
                            <Button title="拍照" onPress={this.handleTakePicButtonClick.bind(this)}/>
                        </View>
                        <View style={{flex: 1, margin: 10}}>
                            <Button title="保存" onPress={this.handleSaveButtonClick.bind(this)}/>
                        </View>
                    </View>
                    {this.state.picSource && (
                        <View>
                            <Image style={{height: 200, width: 200}} source={this.state.picSource}/>
                        </View>
                    )}
                </View>
                <Divider style={{backgroundColor: 'blue'}}/>
                {
                    this.state.logList.length>0&&(
                        <FlatList
                            data={this.state.logList}
                            renderItem={({item}) => this._createListItem(item)}
                        />
                    )
                }
            </ScrollView>
        );
    }
}


const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    row: {
        flexDirection: 'row', flex: 1, padding: 10,
    },
    rowItem: {
        flex: 1, height: 50,
    },
    rowItem2: {
        flex: 9, paddingLeft: 10,
    },
    MapView: {
        flex: 1,
    },
});
